import { Button, ButtonArgs } from "./button"
import { Layout, LayoutArgs, LayoutItem, LayoutItemArgs, LayoutItemCategory } from "./layout"
import { Tree, TreeArgs, TreeItem, TreeItemArgs, TreeItemType } from "./tree"
import { Ajax, AjaxArgs, METHOD_TYPE } from "./ajax"
import { FileInfo } from "./fIleinfo"
import { TextField, TextFieldArgs } from "./textfield"
import { DataProvider } from "./dataprovider"

export class FileSystem {

    /**
     * 保存按钮
     */
    private saveButton: Button;

    /**
     * 下载按钮
     */
    private downloadButton: Button;

    private realPanel: Layout;

    private conPanel: Layout;

    private mainPanel: Layout;

    /**
     * LOGO图片
     */
    private LOGO: HTMLImageElement;

    /**
     *此次树的数据源
    */
    private dataProvider: DataProvider<TreeItem>;

    /**
     * 左侧树
     */
    private tree: Tree;

    /**
     *树控件点击回调
     */
    private treeItemClick: (e: Event, item: Tree | TreeItem) => void | boolean = function (e, item) {
        let realItem = <TreeItem>item;
        let tree: Tree = this.tree;
        let ajaxArgs: AjaxArgs;
        /**
         * 树切换选中
         */
        tree.changeToggleSelect(realItem);
        let file_read: (result: string) => void = function (result) {
            let fileinfo: FileInfo = JSON.parse(result);
            this.textFile.setContent(fileinfo.fileText);
            this.textFile.setExtra(fileinfo);
            this.downloadButton.setUrl("/index?path=" + fileinfo.path);
        }
        if (realItem.type === TreeItemType.FILE) {
            /**
             * 读取数据展示逻辑
             */
            let fileinfo: FileInfo = <FileInfo>realItem.extra;
            let readDataPromise = new Promise((resolve, reject) => {
                ajaxArgs = {
                    url: "/index",
                    jsonPara: fileinfo,
                    resolve: resolve,
                    reject: reject
                };
                Ajax.post(ajaxArgs);
            }).then((data) => {
                let fileinfo: FileInfo = JSON.parse(<string>data);
                this.textFile.setContent(fileinfo.fileText);
                this.textFile.setExtra(fileinfo);
                this.downloadButton.setUrl("/index?path=" + fileinfo.path);
            });
        } else if (realItem.type === TreeItemType.FOLDER) {
            if (realItem.isExpand) {
                //闭合的逻辑
                tree.close(realItem);
            } else {
                //展开的逻辑
                tree.expand(realItem);
            }
        }
    }

    /**
     * 文本框控件
     */
    private textFile: TextField;

    constructor() {

        this._init();
    }

    /**
     * 此处只完成静态页面布局的实例初始化，dataProvider的初始化获取，最后开始dom的挂载
     */
    private _init() {
        this._init_layout();
        this._init_logo();
        this._init_textfile();
        this._init_button();
        this._init_tree();
        let treeArgs: TreeArgs;
        let tree: Tree;
        this._init_dataProvider().then(() => {
            this.tree.setDataProvider(this.dataProvider);
        });
        this._dom_mount();
    }

    /**
     * 初始化树的静态界面
     */
    private _init_tree() {
        /**
         * 因为item需要动态数据设置，所以此处只初始化id和点击事件
         * 如果更改了数据源，需要更换点击事件才能响应正确的行为
         */
        let treeArgs: TreeArgs = {
            id: "tree",
            onclick: this.treeItemClick.bind(this)
        }
        this.tree = new Tree(treeArgs)
    }

    /**
     * 初始化树数据源，之后当promise完成后，才会对tree进行实例化
     */
    private _init_dataProvider(): Promise<any> {
        let ajaxArgs: AjaxArgs;
        return new Promise((resolve, reject) => {
            ajaxArgs = {
                url: "/index",
                resolve: resolve,
                reject: reject
            };
            Ajax.post(ajaxArgs);
        }).then((data) => {
            let fileInfos: FileInfo[] = JSON.parse(<string>data);
            let treeItems: TreeItem[] = [];
            let treeItem: TreeItem;
            let treeItemArgs: TreeItemArgs;
            let tree: Tree;
            let treeArgs: TreeArgs;
            fileInfos.forEach((item, i) => {
                treeItemArgs = {
                    id: item.id,
                    marginGrade: item.marginGrade,
                    text: item.fileName,
                    parentId: item.parentId,
                    type: item.directory ? TreeItemType.FOLDER : TreeItemType.FILE,
                    extra: item
                }
                treeItem = new TreeItem(treeItemArgs);
                treeItems.push(treeItem);
            });
            this.dataProvider = new DataProvider({
                data: treeItems
            })
        })
    }

    /**
     * 初始化button
     */
    private _init_button() {
        let buttonArgs: ButtonArgs;
        let ajaxArgs: AjaxArgs;
        let saveText: (e: Event) => void = function (e: Event) {
            let fileinfo: FileInfo = <FileInfo>this.textFile.extra;
            if (fileinfo === null || fileinfo === undefined) {
                return;
            }
            fileinfo.save = true;
            fileinfo.fileText = (<HTMLTextAreaElement>this.textFile.domBase).value;
            let fileSavePromise = new Promise((resolve, reject) => {
                ajaxArgs = {
                    url: "/index",
                    jsonPara: fileinfo,
                    resolve: resolve,
                    reject: reject
                };
                Ajax.post(ajaxArgs);
            });
            fileSavePromise.then((data) => {
                let fileinfo: FileInfo = JSON.parse(<string>data);
                if (fileinfo.saveStatus) {
                    alert("保存成功")
                } else {
                    alert("保存失败")
                }
            });
        };
        let downloadClick: (e: Event) => void = function (e: Event) {

        };

        buttonArgs = {
            textContent: "保存",
            onclick: saveText.bind(this),
            classList: ["primary"],
            id: "save"
        }
        this.saveButton = new Button(buttonArgs);

        /**
         * 下载按钮
         */
        buttonArgs = {
            textContent: "下载",
            onclick: downloadClick,
            classList: ["primary"],
            id: "download"
        }
        this.downloadButton = new Button(buttonArgs);
    }

    /**
     * 初始化layout
     */
    private _init_layout() {
        /**
         * 初始化mainPanel conPanel  realPanel
         */
        let itemArgs: LayoutItemArgs;
        let layoutArgs: LayoutArgs;
        let realTop: LayoutItem;
        let realSpliter: LayoutItem;
        let realBottom: LayoutItem;
        let conLeft: LayoutItem;
        let conSpliter: LayoutItem;
        let conRight: LayoutItem;
        let mainTop: LayoutItem;
        let mainSpliter: LayoutItem;
        let mainBottom: LayoutItem;


        itemArgs = {
            id: "realTop",
            category: LayoutItemCategory.TOP,
            // height: "5vh"
        }
        realTop = new LayoutItem(itemArgs);
        itemArgs = {
            id: "realSpliter",
            category: LayoutItemCategory.COLUMN_SPLITER,
            width: "98%"
        }
        realSpliter = new LayoutItem(itemArgs);
        itemArgs = {
            id: "realBottom",
            category: LayoutItemCategory.BOTTOM
        }
        realBottom = new LayoutItem(itemArgs);
        layoutArgs = {
            id: "realPanel",
            lay_row: false,
            topItem: realTop,
            bottomItem: realBottom,
            spliterItem: realSpliter
        }
        this.realPanel = new Layout(layoutArgs);



        itemArgs = {
            id: "conLeft",
            category: LayoutItemCategory.LEFT,
            width: "18%"
        }
        conLeft = new LayoutItem(itemArgs);
        itemArgs = {
            id: "conSpliter",
            category: LayoutItemCategory.ROW_SPLITER
        }
        conSpliter = new LayoutItem(itemArgs);
        itemArgs = {
            id: "conRight",
            category: LayoutItemCategory.RIGHT,
            width: "82%"
        }
        conRight = new LayoutItem(itemArgs);
        layoutArgs = {
            id: "conPanel",
            lay_row: true,
            leftItem: conLeft,
            rightItem: conRight,
            spliterItem: conSpliter
        }
        this.conPanel = new Layout(layoutArgs);


        itemArgs = {
            id: "mainTop",
            category: LayoutItemCategory.TOP,
            height: "40px",
            backgroundColor: "#3888ce"
        }
        mainTop = new LayoutItem(itemArgs);
        itemArgs = {
            id: "mainSpliter",
            category: LayoutItemCategory.COLUMN_SPLITER
        }
        mainSpliter = new LayoutItem(itemArgs);
        itemArgs = {
            id: "mainBottom",
            category: LayoutItemCategory.BOTTOM
        }
        mainBottom = new LayoutItem(itemArgs);
        layoutArgs = {
            id: "mainPanel",
            lay_row: false,
            topItem: mainTop,
            bottomItem: mainBottom
        }
        this.mainPanel = new Layout(layoutArgs);
    }

    /**
     * 初始化logo
     */
    private _init_logo() {
        let LOGO = document.createElement("img");
        LOGO.src = "../images/logo.png"
        this.LOGO = LOGO;
    }

    /**
     * 初始化textfile
     */
    private _init_textfile() {
        let textfieldArgs: TextFieldArgs = {
            textContent: " ",
            id: "textfile"
        }
        let textFile = new TextField(textfieldArgs);
        this.textFile = textFile;
    }

    /**
     * 挂载dom，tree数据的异步请求后执行
     */
    private _dom_mount() {
        this.realPanel.setDomParent(this.conPanel.rightItem.domBase);
        this.conPanel.setDomParent(this.mainPanel.bottomItem.domBase);
        this.mainPanel.setDomParent(document.getElementById("content"));
        this.saveButton.setDomParent(this.realPanel.topItem.domBase);
        this.downloadButton.setDomParent(this.realPanel.topItem.domBase);
        this.mainPanel.topItem.domBase.appendChild(this.LOGO);
        this.textFile.setDomParent(this.realPanel.bottomItem.domBase);
        this.tree.setDomParent(this.conPanel.leftItem.domBase);
    }
}